//
//  AudientListViewController.m
//  AudientList
//
//  Created by zhangweiwei on 16/6/15.
//  Copyright © 2016年 Erica. All rights reserved.
//

#import "ZYAudientListViewController.h"
#import "AFNetworking.h"
#import "ZYAudientListCell.h"
#import "YYModel.h"
#import "ZYAudientListModel.h"
#import "KCCategory.h"
#import "ZYAudienListHeaderView.h"
#import "Masonry.h"
#import "ZYAudientListGeneralizeCell.h"
#import "MJRefresh.h"

#import "KCAudioTool.h"

typedef NS_ENUM(NSInteger, ZYLoadDataType) {
    ZYLoadDataTypeRefresh = 0,
    ZYLoadDataTypeLoadMore
};


@interface ZYAudientListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *audientListModels;

@property (nonatomic, strong) ZYAudienListHeaderView *headerView;

@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation ZYAudientListViewController

#pragma mark -懒加载属性
- (ZYAudienListHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [ZYAudienListHeaderView kc_viewFromXib];
    }
    return _headerView;
}

- (NSMutableArray *)audientListModels
{
    if (!_audientListModels) {
        _audientListModels = [NSMutableArray array];
    }
    return _audientListModels;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [_tableView registerClass:[ZYAudientListCell class] forCellReuseIdentifier:ZYAudientListCellReuseID];
        [_tableView registerNib:[ZYAudientListGeneralizeCell kc_xib] forCellReuseIdentifier:ZYAudientListGeneralizeCellReuseID];
        
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
        _tableView.sectionFooterHeight = 0.0001;
        _tableView.sectionHeaderHeight = 5;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 5)];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        KC_WEAK_SELF
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [weakSelf loadDatas:ZYLoadDataTypeRefresh];
        }];
        
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            
            [weakSelf loadDatas:ZYLoadDataTypeLoadMore];
            
        }];
        
    }
    return _tableView;
}

#pragma mark -初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    [self setupConstraint];
    
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)dealloc
{
    [[KCAudioTool shareAudioTool] stopAllAudio];
}

- (void)setupUI
{
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.tableView];
}

- (void)setupConstraint
{
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@44);
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuideBottom);
    }];
    
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);

    }];
}

#pragma mark -加载数据
- (void)loadDatas:(ZYLoadDataType)type
{
    
    NSString *url = [NSString stringWithFormat:@"http://www.51songguo.com/app/newUser/userListV13&newVer=1&page=%zd&pageSize=10&sortType=2&topicType=1", type == ZYLoadDataTypeRefresh ? 1 : self.currentPage + 1];
    
    [[AFHTTPSessionManager manager] GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (type == ZYLoadDataTypeRefresh) {
            
            [self.tableView.mj_header endRefreshing];
        }else {
            
            [self.tableView.mj_footer endRefreshing];
        }
        KCLog(@"%@", responseObject);
        
        NSDictionary *list = responseObject[@"data"][@"list"];
        
        if (type == ZYLoadDataTypeRefresh) {
            [self.audientListModels removeAllObjects];
        }
        
        [self.audientListModels addObjectsFromArray:[NSArray yy_modelArrayWithClass:[ZYAudientListModel class] json:list]];
        
        [self.tableView reloadData];
        
        self.currentPage = type == ZYLoadDataTypeRefresh ? 1 : ++self.currentPage;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (type == ZYLoadDataTypeRefresh) {
            
            [self.tableView.mj_header endRefreshing];
        }else {
            
            [self.tableView.mj_footer endRefreshing];
        }
        KCLog(@"%@", error);
    }];
}


#pragma mark -UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    tableView.mj_footer.hidden = !self.audientListModels.count;
    
    return self.audientListModels.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZYAudientListModel *audientListModel = self.audientListModels[indexPath.section];
    
    if (audientListModel.type == 1) {
        
        ZYAudientListCell *cell = [tableView dequeueReusableCellWithIdentifier:ZYAudientListCellReuseID];
        cell.audientListModel = audientListModel;
        
        [cell setAudienListCellDidClickIntro:^{
            
            audientListModel.open = !audientListModel.isOpen;
            [tableView beginUpdates];
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView endUpdates];
            
        }];
        
        [cell setAudienListCellDidClickAudio:^{
            
            if (audientListModel.isPlayAudio) {
                
                [[KCAudioTool shareAudioTool] playAudioWithUrlStr:audientListModel.audioIntro playFinishHandle:^() {
                    
                    audientListModel.playAudio = NO;
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    
                }];
                
            }else {
                
                [[KCAudioTool shareAudioTool] stopAudioWithUrlStr:audientListModel.audioIntro];
                
            }
            
        }];
        
        return cell;
    }else {
        
        ZYAudientListGeneralizeCell *cell = [tableView dequeueReusableCellWithIdentifier:ZYAudientListGeneralizeCellReuseID];
        
        cell.audientListModel = audientListModel;
        
        return cell;
    }
    
    
}


#pragma mark -UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZYAudientListModel *audientListModel = self.audientListModels[indexPath.section];
    
    return audientListModel.rowHeight;
    
}




@end
